import {Vue, Component} from "vue-property-decorator";

export interface LocalOpts {

}

interface Session {
    uid: string
    token: string
}

@Component
export class VueLocal extends Vue {

    constructor() {
        super()
    }

    isCollapse: boolean = this.GetAttribute('collapse', false);

    SetCollapse(value: boolean) {

        this.SetAttribute('collapse', value);
        this.isCollapse = value;
    }

    GetAttribute<T>(name: string, _default :T) :T {

        let value = this.GetCache<T>(`props.${name}`);

        if(value == null) {
            this.SetAttribute(name,_default);
            return _default
        }

        return value
    }

    SetAttribute<T>(name: string, value: T) {
        this.SetCache(`props.${name}`, value);
        this.$emit('onAttributeChange', name, value)
    }

    SetCache<T = any>(name: string, value: T) {

        localStorage.setItem(name, JSON.stringify(value))
    }

    GetCache<T = any>(name: string): T | null {

        let value = localStorage.getItem(name);

        if (value === null) {
            return null
        }

        return JSON.parse(value)

    }

    DeleteCache(name: string) {
        localStorage.removeItem(name)
    }

    CacheExists(name: string): boolean {
        return this.GetCache(name) !== null;
    }

    UpdateSession(uid: string, token: string) {

        this.SetCache<Session>("session", {
            uid:uid,
            token:token,
        })
    }

    DeleteSession() {
        this.DeleteCache("session")
    }
    GetSession() {
        return this.GetCache<Session>("session")
    }

    CleanSession() {
        this.DeleteCache("session");


    }

    HasSession() : boolean {
        return this.CacheExists("session");
    }

    static install(vue :any, opts? :LocalOpts) {
        vue.prototype.$local = Local;
    }
}

export const Local: VueLocal = new VueLocal();

